package cn.yyh.basic.controller;

import cn.yyh.basic.utils.FastDfsUtil;
import cn.yyh.basic.utils.R;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author 杨永航
 * @version 1.0
 * @Title: FastDfsController
 * @Package: cn.yyh.basic.controller
 * @date 2021/6/29
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    @PostMapping
    public R uploadImg(MultipartFile file) {
        try {
            // 获取到当前上传文件的字节数组
            byte[] bytes = file.getBytes();

            // 获取上传文件的后缀名
            String filename = file.getOriginalFilename();
            String name = filename.substring(filename.lastIndexOf(".") + 1);

            // fastDfs上传需要两个参数:1.文件字节数组,2.后缀名
            String path = FastDfsUtil.upload(bytes, name);

            // 把路径返回给前端,用来表单提交存放到数据库
            return R.oK().setResultObj(path);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error();
        }
    }

    @DeleteMapping
    public R deleteImg(@RequestParam String path) {
        try {
            String groupName = path.substring(0,path.indexOf("/"));
            String fileName = path.substring(path.indexOf("/") + 1);
            FastDfsUtil.delete(groupName, fileName);
            return R.oK();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }
}
